package com.wunu.smartlock1;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.wunu.smartlock1.activity.AuthorizedLockActivity;
import com.wunu.smartlock1.activity.LockRecordActivity;
import com.wunu.smartlock1.activity.QrcodeActivity;
import com.wunu.smartlock1.activity.ScanListActivity;
import com.wunu.smartlock1.activity.TemporyLockActivity;
import com.wunu.smartlock1.bluetooth.WunuBlueManager;
import com.wunu.smartlock1.bluetooth.command.OpenLockSetp2Command;
import com.wunu.smartlock1.bluetooth.command.OpenLockStep1Command;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockEventApi;
import com.wunu.smartlock1.net.api.LockManageApi;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.ApiSimpleResponse;
import com.wunu.smartlock1.net.response.LockItem;
import com.wunu.smartlock1.util.CommonUtil;
import com.wunu.smartlock1.xxtea.XXTEA;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

public class MainActivity_success extends AppCompatActivity implements OnClickListener{
    LockEventApi service = NetComponent.getRetrofit().create(LockEventApi.class);
    String toast;
    private ViewPager viewPager;
    private LinearLayout ll_item;//灰点所在的线性布局
    private ImageView blue_iv;//小蓝点
    int position;//当前界面数（从0开始）
    private int pointWidth;//小灰点的距离
    private List<View> contentList = new ArrayList<View>();


    //
    View inflate;
    Dialog dialog;
    Intent intent = new Intent();
    ImageView a_addButton;//添加新锁
    ImageView a_memberButton;//家庭成员
    ImageView a_temporaryKeyButton;//临时秘钥
    ImageView a_authorizedButton;//授权成员
    ImageView a_lockEventButton;//开锁记录
    ImageView a_lockQRCodeButton;//锁二维码

    ImageView b_addButton;//添加新锁
    ImageView b_memberButton;//家庭成员
    ImageView b_temporaryKeyButton;//临时秘钥
    ImageView b_authorizedButton;//授权成员
    ImageView b_lockEventButton;//开锁记录
    ImageView b_lockQRCodeButton;//锁二维码

    ImageView c_addButton;//添加新锁
    ImageView c_memberButton;//家庭成员
    ImageView c_temporaryKeyButton;//临时秘钥
    ImageView c_authorizedButton;//授权成员
    ImageView c_lockEventButton;//开锁记录
    ImageView c_lockQRCodeButton;//锁二维码

    TextView cancelView;//取消
    TextView resetView;//重置秘钥
    TextView stopView;//停用蓝牙解锁
    TextView deleteView;//删除门锁

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            System.out.println("msg----------------------->:"+msg);
            System.out.println("obj->"+msg.getData());
            if (msg == null || msg.obj == null){
                Toast.makeText(MainActivity_success.this, toast+"失败", Toast.LENGTH_SHORT).show();
            }
            ApiSimpleResponse.ApiSimpleData simpleData = (ApiSimpleResponse.ApiSimpleData) msg.obj;
            System.out.println("obj:"+simpleData.getCode()+"\t"+simpleData.getMsg());
            if (simpleData.getCode() == 200 && "ok".equals(simpleData.getMsg())){
                Toast.makeText(MainActivity_success.this, toast+"成功", Toast.LENGTH_SHORT).show();
            }
            Toast.makeText(MainActivity_success.this, toast+"失败,"+simpleData.getMsg(), Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//设置App不显示菜单，黑乎乎的不好看
        //注意这两句代码的顺序，上面一句写在下面一句后面会报错
        setContentView(R.layout.smartlock_activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        ll_item = (LinearLayout) findViewById(R.id.ll_item);
        blue_iv = (ImageView) findViewById(R.id.blue_iv);

        //添加页面
        View viewa = LayoutInflater.from(this).inflate(R.layout.smartlock_lock_list, null);
        View viewb = LayoutInflater.from(this).inflate(R.layout.smartlock_lock_list_unlock, null);
        View viewc = LayoutInflater.from(this).inflate(R.layout.smartlock_lock_list_locked, null);
        contentList.add(viewa);
        contentList.add(viewb);
        contentList.add(viewc);

        a_addButton = viewa.findViewById(R.id.addButton);
        a_memberButton = viewa.findViewById(R.id.memberButton);
        a_temporaryKeyButton = viewa.findViewById(R.id.temporaryKeyButton);
        a_authorizedButton = viewa.findViewById(R.id.authorizedButton);
        a_lockEventButton = viewa.findViewById(R.id.lockEventButton);
        a_lockQRCodeButton = viewa.findViewById(R.id.lockQRCodeButton);
        a_addButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                System.out.println("添加新锁");
                Log.v("添加新锁", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, ScanListActivity.class));
            }
        });
        a_memberButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("家庭成员", "list 1:" );
                memberShow();
            }
        });
        a_temporaryKeyButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("临时秘钥", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, TemporyLockActivity.class));
            }
        });
        a_authorizedButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("授权成员", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, AuthorizedLockActivity.class));
            }
        });
        a_lockEventButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("开锁记录", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, LockRecordActivity.class));
            }
        });
        a_lockQRCodeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("锁二维码", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, QrcodeActivity.class));
            }
        });
        b_addButton = viewb.findViewById(R.id.addButton);
        b_memberButton = viewb.findViewById(R.id.memberButton);
        b_temporaryKeyButton = viewb.findViewById(R.id.temporaryKeyButton);
        b_authorizedButton = viewb.findViewById(R.id.authorizedButton);
        b_lockEventButton = viewb.findViewById(R.id.lockEventButton);
        b_lockQRCodeButton = viewb.findViewById(R.id.lockQRCodeButton);
        ImageView hitUnlock = viewb.findViewById(R.id.hitUnlock);
        hitUnlock.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("点击了解锁按钮");
                        //开线程加载数据
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                System.out.println("device:"+CommonUtil.device.getName()+"\t"+CommonUtil.device.getMac());
                                System.out.println("---------------open lock step 1----------->blcmd begin");
                                //int baseCode = CommonUtil.createBaseCode();
                                int baseCode = 648845;
                                int openId = CommonUtil.createBaseCode();
                                int[] v = {0,openId};
                                int[] k = {0,0,0,baseCode};
                                OpenLockStep1Command o1cmd = new OpenLockStep1Command(XXTEA.encrypt(v,k));
                                WunuBlueManager manager = WunuBlueManager.Companion.getShared();
                                manager.setCommand(o1cmd);
                                manager.connectDevice(CommonUtil.device);
                                System.out.println("----------------open lock step 1---------->blcmd end");
                                System.out.println("map1:"+CommonUtil.map);
                                try{
                                    Thread.sleep(10000);
                                }catch (Exception e){}
                                System.out.println("map2:"+CommonUtil.map);
                                System.out.println("n=  "+CommonUtil.map.get("n"));

                                int sn = CommonUtil.map.get("n")==null?0:(int)CommonUtil.map.get("n");
                                int[] sv = {0,CommonUtil.getSufPrime(baseCode,sn)};
                                int[] sk = {0,0,0,CommonUtil.getPrePrime(baseCode,sn)};
                                OpenLockSetp2Command o2cmd = new OpenLockSetp2Command(XXTEA.encrypt(sv,sk));

                                System.out.println("---------------open lock step 2----------->blcmd begin");
                                manager.setCommand(o2cmd);
                                manager.connectDevice(CommonUtil.device);
                                System.out.println("------------open lock step 2-------------->blcmd end");
                                System.out.println("map1:"+CommonUtil.map);
                                try{
                                    Thread.sleep(10000);
                                }catch (Exception e){}
                                System.out.println("map2:"+CommonUtil.map);
                                System.out.println("success=  "+CommonUtil.map.get("success"));

                                /*try {
                                    Call<ApiSimpleResponse> call = service.sendOpenLockResult(1, 1);//event : 1成功，-1失败，-2（wx-ios）,-3(wx-android)
                                    ApiSimpleResponse resp = call.execute().body();
                                    // 发送消息，把服务器返回的本文弹出吐司显示
                                    Message msg = handler.obtainMessage();
                                    if(resp == null || resp.getData() == null)msg.obj = null;
                                    else msg.obj = resp.getData();
                                    toast = "解锁";
                                    System.out.println(toast+":"+msg.obj);
                                    handler.sendMessage(msg);
                                } catch (Exception e) {
                                    System.out.println(toast + e);
                                }*/
                            }
                        }.start();
            }
        });
        b_addButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("添加新锁", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, ScanListActivity.class));
            }
        });
        b_memberButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("家庭成员", "list 1:" );
                memberShow();
            }
        });
        b_temporaryKeyButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("临时秘钥", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, TemporyLockActivity.class));
            }
        });
        b_authorizedButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("授权成员", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, AuthorizedLockActivity.class));
            }
        });
        b_lockEventButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("开锁记录", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, LockRecordActivity.class));
            }
        });
        b_lockQRCodeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("锁二维码", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, QrcodeActivity.class));
            }
        });
        c_addButton = viewc.findViewById(R.id.addButton);
        c_memberButton = viewc.findViewById(R.id.memberButton);
        c_temporaryKeyButton = viewc.findViewById(R.id.temporaryKeyButton);
        c_authorizedButton = viewc.findViewById(R.id.authorizedButton);
        c_lockEventButton = viewc.findViewById(R.id.lockEventButton);
        c_lockQRCodeButton = viewc.findViewById(R.id.lockQRCodeButton);
        c_addButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("添加新锁", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, ScanListActivity.class));
            }
        });
        c_memberButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("家庭成员", "list 1:" );
                memberShow();
            }
        });
        c_temporaryKeyButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("临时秘钥", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, TemporyLockActivity.class));
            }
        });
        c_authorizedButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("授权成员", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, AuthorizedLockActivity.class));
            }
        });
        c_lockEventButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("开锁记录", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, LockRecordActivity.class));
            }
        });
        c_lockQRCodeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.v("锁二维码", "list 1:" );
                startActivity(intent.setClass(MainActivity_success.this, QrcodeActivity.class));
            }
        });

        //将图片的引用转化为图片控件存在List的集合中
        for(int i=0;i<contentList.size();i++){
            //绘制小灰点儿，有几个界面就绘制几个
            ImageView points = new ImageView(this);
            points.setImageResource(R.drawable.grey_point);//通过shape文件绘制好灰点
            //给第一个以外的小灰点儿设置左边距，保证三个灰点水平居中
            LinearLayout.LayoutParams lllp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);//拿到灰点所处的线性布局一样的形状（一些距离属性）
            if(i>0)
                lllp.leftMargin = 30;//设置左外边距，像素
            points.setLayoutParams(lllp);//把设置好左外边距的形状设置给灰点
            ll_item.addView(points);//将灰点加入线性布局
        }
        //为了完成蓝点在界面滑动时的动画效果，必须获取到灰点的边距，通过动态的给蓝点设置边距来完成动画效果
        //由于在执行onCreate方法时，界面还没有绘制完成，无法获取pointWidth，设定小蓝点绘制完成的事件监听，当小蓝点绘制完成再获取
        blue_iv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //获取小灰点圆心间的距离，第1个灰点和第二个灰点的距离
                pointWidth = ll_item.getChildAt(1).getLeft()-ll_item.getChildAt(0).getLeft();
            }
        });

        VPAdapter vpAdapter = new VPAdapter();//创建适配器
        viewPager.setAdapter(vpAdapter);//ViewPager加载适配器
        //为ViewPager设定监听器，界面是滑动时让蓝点也跟着动
        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            //当前选中第几个界面
            public void onPageSelected(int arg0) {
                position = arg0;
            }
            /**
             * 界面滑动时回调此方法
             * arg0:当前界面数
             * arg1:界面滑动过的百分数（0.0-1.0）
             * arg2:当前界面偏移的像素位置
             */
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                int width;//小蓝点当前滑动距离
                width = (int) (arg1*pointWidth+arg0*pointWidth);//1个界面就要一个小灰点的距离，再加上滑动过的百分比距离就是当前蓝点的位置
                LayoutParams rllp= (LayoutParams) blue_iv.getLayoutParams();//拿到蓝点所在布局的形状
                rllp.leftMargin=width;//设置蓝点的左外边距
                blue_iv.setLayoutParams(rllp);//将设置好的形状设置给蓝点
            }
            //状态改变时调用：arg0=0还没滑动,arg0=1正在滑动,arg0=2滑动完毕
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    class VPAdapter extends PagerAdapter{
        //返回ViewPager中总页数
        @Override
        public int getCount() {
            return contentList.size();
        }
        //判断视图是否由对象生成
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }
        @Override
        /**
         * 返回将哪一个对象放在当前ViewPager中
         * container：每一页的父容器
         * position：当前页（从0开始）
         */
        public Object instantiateItem(ViewGroup container, int position) {
            //浪费资源，每次滑到新的页都会创建新的的ImageView，我们选择先把ImageView控件存在List集合中，再按需要获取
            View content = contentList.get(position);
            container.addView(content);
            return content;
        }
        @Override
        /**
         * 从ViewPager中移除View对象
         */
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }


    public void memberShow(){
        dialog = new Dialog(this,R.style.smartlock_ActionSheetDialogStyle);
        inflate = LayoutInflater.from(this).inflate(R.layout.smartlock_buttom_dialog, null);
        cancelView = inflate.findViewById(R.id.cancel);//取消弹框
        resetView = inflate.findViewById(R.id.resetlock);//取消弹框
        deleteView = inflate.findViewById(R.id.deletelock);//取消弹框
        stopView = inflate.findViewById(R.id.stoplock);//取消弹框
        resetView.setOnClickListener(this);
        cancelView.setOnClickListener(this);
        deleteView.setOnClickListener(this);
        stopView.setOnClickListener(this);
        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity( Gravity.BOTTOM);
        dialog.show();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.cancel){
            dialog.dismiss();
        }else if(id == R.id.resetlock){
            Toast.makeText(this,"点击了重置秘钥按钮",Toast.LENGTH_SHORT).show();
        }else if(id == R.id.deletelock){
            Toast.makeText(this,"点击了删除门锁按钮",Toast.LENGTH_SHORT).show();
        }else if(id == R.id.stoplock){
            Toast.makeText(this,"点击了停用蓝牙解锁按钮",Toast.LENGTH_SHORT).show();
        }
        //dialog.dismiss();
    }
    /*
    * 拉取锁列表
    * */
    private void fetchLockList() {
        LockManageApi api = NetComponent.getRetrofit().create(LockManageApi.class);
        Call<ApiNormalResponse<List<LockItem>>> call = api.getLockList( );
        try {
            ApiNormalResponse<List<LockItem>> resp = call.execute().body();
            Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg){
                    List<LockItem> locks = (List<LockItem>)msg.obj;
                    System.out.println("锁列表" + locks);
                    // TODO: - 显示锁列表
                    
                }
            };
            Message msg = handler.obtainMessage();
            if(resp == null || resp.getData() == null)msg.obj = null;
            else msg.obj = resp.getData().getData();
            handler.sendMessage(msg);

        } catch (Exception e) {
            System.out.println("开锁异常" + e);
        }

    }
}
